<template>
  <div class="app-container">
    <!--模糊查询表单-->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" size="mini">

      <el-form-item label="部门名称：">
        <el-input v-model="formInline.deptName" placeholder="请输入部门名称" clearable />
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="formInline.status" placeholder="部门状态">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
    </el-row>

    <br>
    <!--表格数据-->
    <el-table
      v-if="refreshTable"
      :data="deptList"
      :default-expand-all="isExpandAll"
      style="width: 100%;margin-bottom: 20px;"
      row-key="deptId"
      border
      :tree-props="{children: 'depts'}"
    >
      <el-table-column
        prop="deptName"
        label="部门名称"
        sortable
        width="150"
        align="center"
      />

      <el-table-column
        prop="orderNum"
        label="排序"
        width="120"
        align="center"
      />

      <el-table-column
        prop="status"
        label="状态"
        width="120"
        align="center"
      >
<!--        <template slot-scope="scope">-->
<!--          <el-tag :type=" scope.row.status == '0'?  '':'warning'">{{ scope.row.status == '0'?'正常':'停用' }}</el-tag>-->
<!--        </template>-->

          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :disabled="!(displayed(scope.row))" :content="displayed(scope.row)"
                        placement="top">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :disabled="(displayed(scope.row)) == ''? false:true"
              @change="switchStatus($event,scope.row)">
            </el-switch>
            </el-tooltip>
          </template>


      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            :disabled="scope.row.depts =='' ||  scope.row.ancestors.split(',').length > 2"
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="!(scope.row.depts =='' || scope.row.ancestors.split(',').length > 2) "
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table><l />
    <!--增加修改数据表单数据-->
    <!-- 表单对话框 -->
    <el-button type="text" @click="dialogFormVisible = true" />
    <el-dialog :title="this.formTile" :visible.sync="dialogFormVisible">
      <el-form ref="deptForm" :model="deptForm" label-width="80px" :rules="rules">
        <el-form-item label="上级菜单" prop="parentId">
          <treeselect
            v-model="deptForm.parentId"
            placeholder="请选择上级菜单"
            :options="menuOptions"
            :normalizer="normalizer"
            :show-count="true"
          />
        </el-form-item>

        <el-form-item label="部门名称" style="display: inline-block" prop="deptName">
          <el-input v-model="deptForm.deptName" placeholder="请输入部门名称" style="width: 275px" />
        </el-form-item>

        <el-form-item label="显示排序" style="display: inline-block;margin-left: 25px" prop="orderNum">
          <el-input-number v-model="deptForm.orderNum" style="width: 250px;" controls-position="right" :min="1" :max="20" @change="handleChange" />
        </el-form-item>

        <el-form-item label="负责人" style="display: inline-block;width:360px">
          <el-input v-model="deptForm.leader" placeholder="请输入负责人" />
        </el-form-item>

        <el-form-item label="联系电话" style="display: inline-block;width:360px" prop="phone">
          <el-input v-model="deptForm.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="邮箱" style="display: inline-block;width:360px" prop="email">
          <el-input v-model="deptForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-tooltip class="item" effect="dark"  content="请在首页进行状态的修改哦！"
                    placement="top">

          <el-form-item label="部门状态" style="display: inline-block;margin-left: 25px">
            <el-radio v-model="deptForm.status" label="0" disabled>正常</el-radio>
            <el-radio v-model="deptForm.status" label="1" disabled>停用</el-radio>
          </el-form-item>
        </el-tooltip>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save('deptForm')">确定</el-button>
        <el-button type="danger" @click="resetForm('deptForm')">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import store from '../../../store'

import { parseTime } from '../../../utils'
// 引入treeselect
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {checkDeptHasPerson} from "../../../api/dept";

export default {
  name: 'Index',
  components: { Treeselect },
  data() {
    var validatePhone = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!regMobile.test(value)) {
        callback(new Error('手机号码不正确!'))
      } else {
        callback()
      }
    }
    return {

      /* 当前用户名字*/
      userName: '',
      /* 表单规则*/
      rules: {
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在2到 6 个字符', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '请输入显示顺序', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { validator: validatePhone, trigger: 'change' },
          { min: 11, max: 11, message: '手机号长度不正确！', trigger: ['blur', 'change'] }
        ]
      },
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      loading: false, // 遮罩层
      deptList: [],
      // 数据集合
      deptForm: {
          deptId: '-1',
          parentId: '0',
          ancestors: undefined,
          deptName: undefined,
          orderNum: undefined,
          leader: undefined,
          email: undefined,
          status: '0',
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
      },
      dialogFormVisible: false, // 表单隐藏
      menuOptions: [], // 菜单树数据
      formTile: '', // 表单表头
      // 模糊查询表单数据
      formInline: {
        deptName: '',
        status: ''
      }

    }
  },

  created() {
    this.loadDeptsList()

  },
  methods: {
      // 判断当前状态是否停用

      displayed(row){
          if(row.depts != ''){
              return '以下还有部门，不能禁用哦'
          }else{
              return ''
          }

      },

      //切换状态
      switchStatus($event,row){
          console.log(row)
          this.axios.get("/sysDept/select/"+row.deptId).then(result => {
              console.log(result)
              if(!result.data.data){
                  this.$message({
                      message: '该部门下还有成员，不能禁用哦',
                      type: 'warning',
                      duration: 2000, // 显示时间, 毫秒。
                  });
                  this.loadDeptsList();

              }else {
                  console.log(row)
                  this.deptForm = row
                  console.log(this.deptForm)
                  this.axios.put('/sysDept/dept',
                      this.deptForm).then(result => {
                        this.$message({
                            message: '更改状态成功',
                            type: 'success',
                            duration: 2000, // 显示时间, 毫秒。

                        });
                      this.loadDeptsList() // 加载页面

                  });
              }
          })
      },

    // 模糊查询提交按钮
    onSubmit() {
      this.loadDeptsList()
    },
    // 重置按钮
    reset() {
      this.formInline = {
        deptName: '',
        status: ''
      }
    },

    // 保存按钮
     save(formName) {
         this.$refs[formName].validate((valid) => {
           if (valid) {
          // 新增
            if (this.deptForm.deptId == -1) {
            // 新增
            console.log(this.deptForm);
            this.deptForm.deptId = '';
              this.axios.post('/sysDept/dept', this.deptForm
            ).then(result => {
              console.log(result.data);
              if (result.data.data == 'ok') {
                this.$message({
                  message: '添加成功',
                  type: 'success',
                  duration: 2000, // 显示时间, 毫秒。

                });
                  this.resetForm(formName);
                  this.loadDeptsList() // 加载页面

              }
            })
          } else {
            // 修改
            console.log(this.deptForm);
               this.axios.put('/sysDept/dept', this.deptForm
            ).then(result => {
              console.log(result.data)
              if (result.data.data == 'ok') {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 2000 // 显示时间, 毫秒。
                });
                this.resetForm(formName);
                this.loadDeptsList() // 加载页面
              }
            })
          }
          // 清除表单数据
          this.clear();
          // 关闭表单
          this.dialogFormVisible = false
        }
      })
    },
    /* 表单显示顺序*/
    handleChange(value) {
      console.log(value)
    },

    // 获取数据
    async loadDeptsList() {
      this.loading = true
      await this.axios.get('/sysDept/dept/',
        {
          params: {
            deptName: this.formInline.deptName,
            status: this.formInline.status
          }
        }).then(result => {
        console.log(result.data)
        this.loading = false
        // 处理后台数据(将后台result.data数据与deptList集合绑定)
        this.deptList = result.data.data
        this.menuOptions = this.deptList
          console.log(this.deptList)
      })
    },

    // 转换树结构
    normalizer(node) {
      if (node.depts && !node.depts.length) {
        delete node.depts
      }
      if (node.deptName == undefined) {
        node.deptName = '主目录'
      }
      console.log(node.hasOwnProperty('depts'))
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.depts,
        isDisabled: !(node.hasOwnProperty('depts'))

      }
    },
    // 折叠菜单
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },

    // 修改(数据回显)
    handleUpdate(row) {
      this.dialogFormVisible = true
      this.formTile = '修改部门'
      this.deptForm.updateBy = this.userName
      this.deptForm.parentId = row.deptId
      this.deptForm = JSON.parse(JSON.stringify(row)) // 将row对象解析后赋值给表单对象
    },

    // 删除
      async handleDelete(row) {
      console.log(row)
      this.deptForm.deptId = row.deptId
        await this.$confirm('确定删除' + row.deptName + '这一项数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
         this.axios.delete('/sysDept/dept/' + this.deptForm.deptId
        ).then(result => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新当前页
          this.loadDeptsList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 新增
    handleAdd(row) {
      this.dialogFormVisible = true
      /* 获取当前用户名*/
      const user = store.getters.name
      this.userName = user
      this.deptForm.createBy = this.userName
      this.formTile = '新增部门'
      this.deptForm.parentId = row.deptId
    },

      //关闭表单
    resetForm(formName) {
        // 重置
        this.$refs[formName].clearValidate();
        this.clear();
        this.dialogFormVisible = false

    },
    clear() {
      this.deptForm = {
        deptId: '-1',
        parentId: '0',
        ancestors: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        email: undefined,
        status: '0',
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      },
      this.formTile = ''

    },

    /* 格式化时间*/
    parseTime(time) {
      var date = new Date(time);
      return parseTime(date)
    }
  }
}

</script>
<style scoped>

</style>
